export function storePrivateMessage(message) {
    const messages = JSON.parse(localStorage.getItem('privateMessages') || '{}');
    const chatKey = getChatKey(message.sender, message.receiver);

    const newMsg = {
        sender: message.sender,
        content: message.content,
        timestamp: new Date().getTime()
    };

    if (!messages[chatKey]) {
        messages[chatKey] = [];
    }

    // 检查是否已存在相同内容的消息，避免重复存储
    const isDuplicate = messages[chatKey].some(
        msg => msg.content === message.content && msg.sender === message.sender
    );

    if (!isDuplicate) {
        messages[chatKey].push(newMsg);
        localStorage.setItem('privateMessages', JSON.stringify(messages));

        // 触发全局事件，包含完整消息信息和聊天键
        window.dispatchEvent(new CustomEvent('newPrivateMessage', {
            detail: {
                chatKey,
                message: newMsg,
                isNew: true
            }
        }));
    }
}

export function getChatKey(user1, user2) {
    // 确保无论发送方和接收方顺序如何，都能生成相同的key
    return [user1, user2].sort().join('_');
}